<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class UpdateSmsSendLog extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'UpdateSmsSendLog';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新短信发送详情每分钟执行';

    protected $successLog = 'SendAllSms'; //日志
    protected $errorLog = 'error_SendAllSms'; //错误日志
    protected $apiCon = 'api'; //数据库
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //查询回执状态第三方短信
        $res = curl_request(getKkaudioApiUrl() . '/inner/sms/sendSmsStatus', [], 'json', 'POST');
        write_log("CheckouRes", "第三方数据返回", $res);
        if ($res['code'] != 0) {
            write_log($this->successLog, "查询状态为空", '');
            return false;
        }
        $phoneStatusArr = $res['data']['data'];
        $insert = [];
        foreach ($phoneStatusArr as $k => $v) {
            //查询数据库是否存在此msgid
            $smsdata = DB::connection($this->apiCon)->table('sms_alls')->where('msgId', $v['msgId'])->first(['id']);
            $smsdata = objToArray($smsdata);
            if (!empty($smsdata)) {
                //数组预处理
                $insert[$k]['phone'] = $v['phone'];
                $insert[$k]['receiveTime'] = $v['receiveTime'];
                $insert[$k]['status'] = $v['status'];
                $insert[$k]['smsid'] = $smsdata['id'];
            }
        }
        DB::beginTransaction();
        try {
            //插入群发log中
            DB::connection($this->apiCon)->table('sms_all_log')->insert($insert);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            write_log($this->errorLog, "发送信息入库失败", $e->getMessage());
        }

    }
}
